package com.yunfeisoft.business.dao.impl.postgres;

import com.applet.base.ServiceDaoImpl;
import com.applet.sql.builder.SelectBuilder;
import com.applet.sql.builder.WhereBuilder;
import com.applet.utils.Page;
import com.yunfeisoft.business.dao.inter.SmsCouponDao;
import com.yunfeisoft.business.model.PmsProduct;
import com.yunfeisoft.business.model.SmsCoupon;
import com.yunfeisoft.business.model.SmsCouponProductCategoryRelation;
import com.yunfeisoft.business.model.SmsCouponProductRelation;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * ClassName: SmsCouponDaoImpl
 * Description: 优惠卷表Dao实现
 * Author: Jackie liu
 * Date: 2020-06-02
 */
@Repository
public class SmsCouponDaoImpl extends ServiceDaoImpl<SmsCoupon, String> implements SmsCouponDao {

    @Override
    public Page<SmsCoupon> queryPage(Map<String, Object> params) {
        WhereBuilder wb = new WhereBuilder();
        if (params != null) {
            if (!ObjectUtils.isEmpty(params.get("name"))) {
                wb.andEquals("name", params.get("name"));
            }
            initPageParam(wb, params);
        }
        return queryPage(wb);
    }

    /**
     * 根据商品id查询优惠券列表
     * @param productId
     * @return
     */
    @Override
    public List<SmsCoupon> queryListByProductId(String productId) {
        WhereBuilder wb = new WhereBuilder();
        wb.andEquals("pc.productId", productId);
        wb.andLessEquals("c.startTime", new Date());
        wb.andGreaterEquals("c.endTime", new Date());
        SelectBuilder builder = getSelectBuilder("c");
        builder.join(SmsCouponProductRelation.class)
                .alias("pc")
                .on("pc.couponId = c.id")
                .build();
        return query(builder.getSql(), wb);
    }

    /**
     * 查询符合条件指定分类的优惠券
     * @param productId
     * @return
     */
    @Override
    public List<SmsCoupon> queryListByCategory(String productId) {
        WhereBuilder wb = new WhereBuilder();
        wb.andEquals("p.productId", productId);
        wb.andLessEquals("c.startTime", new Date());
        wb.andGreaterEquals("c.endTime", new Date());
        SelectBuilder builder = getSelectBuilder("c");
        builder
                .join(SmsCouponProductCategoryRelation.class).alias("pcr")
                .on("pcr.couponId = c.id").build()
                .join(PmsProduct.class).alias("p")
                .on("p.categoryId = pcr.categoryId").build();
        return query(builder.getSql(), wb);
    }

    /**
     * 查询所有通用的优惠券
     * @return
     */
    @Override
    public List<SmsCoupon> queryListCommon() {
        WhereBuilder wb = new WhereBuilder();
        wb.andEquals("useType", 0);
        wb.andLessEquals("startTime", new Date());
        wb.andGreaterEquals("endTime", new Date());
        return query(wb);
    }
}